#!/bin/sh

MY_SOFTS=/usr/local/mysofts

if [ ! -d $MY_SOFTS ]; then
    mkdir -p $MY_SOFTS
fi
cd $MY_SOFTS

jdkfile=$(ls | grep jdk-*-linux-*.gz)
jdkdirname="jdk1.8.0_141"

# 如果目录下没有jdk安装包那么就下载
if [ ! -f "$jdkfile" ]; then
   echo "正在下载jdk请稍等..."
   wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u141-b15/336fa29ff2bb4ef291e347e091f7f4a7/jdk-8u141-linux-x64.tar.gz"
else
   echo "不需要下载JDK,已经存在"$jdkfile
fi

# 判断解压的文件是否存在
if [ ! -d "/usr/local/mysofts/jdk1.8.0_141" ]; then
    tar -zxvf jdk-8u141-linux-x64.tar.gz
else
    rm  -rf "/usr/local/mysofts/jdk1.8.0_141"
    tar -zxvf jdk-8u141-linux-x64.tar.gz
fi


# sed -i模式是在原来的基础上进行修改
# set "2/d" /etc/profile是删除第二行
# sed "/JAVA_HOME/d" /etc/profile是删除文件中的匹配JAVA_HOME的行删除
sed -i '/export JAVA_HOME/d;/export CLASS_PATH/d;/export JRE_HOME/d;/export PATH/d' /etc/profile
chmod 775 /etc/profile

cat >> /etc/profile <<"EOF"
export JAVA_HOME=/usr/local/mysofts/jdk1.8.0_141
export JRE_HOME=$JAVA_HOME/jre
export CLASS_PATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib
export PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin
EOF

source /etc/profile

echo "测试是否安装成功"
java -version
echo "安装成功"